package com.example.emos.wx.config.shrio;

import com.example.emos.wx.db.pojo.TbUser;
import com.example.emos.wx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 让这个类能被springboot识别到，加这个注解
 */
@Component
public class OAuth2Reaml extends AuthorizingRealm {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    /**\
     * 判断你传入的令牌字符串符不符合我的要求
     * @param token 令牌对象
     * @return boolean
     */
    @Override
    public boolean supports(AuthenticationToken token){
        return token instanceof OAuth2Token;
    }

    /**
     * 授权
     * @param collection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
        //获得用户的基本信息，因为是先认证之后才传给授权
        TbUser user = (TbUser) collection.getPrimaryPrincipal();
        int userId = user.getId();
        // 查询用户的权限列表
        Set<String> permsSet = userService.searchUserPermissions(userId);

        //创建授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //把权限列表添加到info对象中
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(验证登录的时候调用)
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //获得token字符串
        String accessToken = (String) token.getPrincipal();
        int userId = jwtUtil.getUserId(accessToken);
        TbUser user = userService.searchById(userId);

        if (user == null){
            throw new LockedAccountException("账号已被锁定，请联系管理员");
        }
        //创建认证对象
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
        //TODO 往info对象中添加用户信息、token字符串

        return info;
    }


}
